<?php
require_once 'modules/dao/constants.php';

class Connection {

    /**
     * 数据库连接
     * @author liuhui 2009-6-12
     */
    
    # 配置开发级别数据库
    private function setDevelopment () {
        $database = array();
        $database[Consts::F_DBHOST] = 'localhost';
        $database[Consts::F_DBUSER] = 'root';
        $database[Consts::F_DBPASS] = '';
        $database[Consts::F_DBNAME] = 'igrid_new';
        return $database;
    }

    # 配置产品级别数据库
    private function setProduction () {
        $database = array();
        $database[Consts::F_DBHOST] = 'localhost';
        $database[Consts::F_DBUSER] = 'root';
        $database[Consts::F_DBPASS] = '';
        $database[Consts::F_DBNAME] = 'igrid_new';
        return $database;
    }
    
    protected $connection = null;
    protected $config = null;
    protected static $instance = null; # 需要使用静态常量

    
    public static function getInstance () {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    # 获取数据库链接
    public function getConnection () {
        if ($this->connection) {
            return $this->connection;
        }
        return $this->setConnection();
    }

    # 关闭数据库链接
    public function closeConnection () {
        $this->connection = null;
    }

    # 设置数据库链接
    private function setConnection () {
        $this->getConfig();
        try {
            $dns = sprintf('mysql:host=%s;dbname=%s', $this->config[Consts::F_DBHOST], $this->config[Consts::F_DBNAME]);
            $this->connection = new PDO($dns, $this->config[consts::F_DBUSER], $this->config[consts::F_DBPASS]);
        } catch (Exception $e) {
            throw new Exception('cann`t connection database,error as :' . $e);
        }
        return $this->connection;
    }

    # 获取数据库配置
    public function getConfig () {
        $configs = array();
        $configs[Consts::D_DEVELOPMENT] = $this->setDevelopment();
        $configs[Consts::D_PRODUCTION] = $this->setProduction();
        return $this->config = $configs[Consts::LEVEL];
    }

}
?>